package plugin

import (
	"io"
	"log/slog"
	"os"

	"gitee.com/mkwchecking/k-scaffold/config"
	"gitee.com/mkwchecking/k-scaffold/pkg/rely/ioutils"
	"gitee.com/mkwchecking/k-scaffold/pkg/rely/log"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
)

func (p *Plugins) GetLogger() (*log.Logger, error) {
	if p._log != nil {
		return p._log, nil
	}

	conf := config.Get().Logger
	appConf := config.Get().App

	var loggerWriter io.WriteCloser
	loggerWriter = os.Stdout
	if conf.File != "" {
		rotate, err := rotatelogs.New(conf.File, rotatelogs.WithClock(rotatelogs.Local))
		if err != nil {
			return nil, err
		}

		loggerWriter = ioutils.MultiWriteCloser(os.Stdout, rotate)
	}

	l := log.New(
		log.WithLevel(log.Level(conf.Level)),
		log.WithFormat(log.Format(conf.Format)),
		log.WithWriter(loggerWriter),
		log.WithAttrs([]slog.Attr{
			slog.String("host", appConf.Host.String()),
			slog.String("app", appConf.Name),
			slog.String("env", appConf.Env.String()),
		}),
	)

	p._log = log.NewLogger(l)
	return p._log, nil
}
